package es.ceura.wilder;

import es.ceura.wilder.configuration.Config;
import es.ceura.wilder.controllers.Controller;
import es.ceura.wilder.logger.Logger;
import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;

/**
 *
 * @author Jorge Madrid
 */
public class Wilder {

    private ServerSocket serverSocket;
    private volatile boolean running = false;
    private Controller controller;
    private Logger logger;

    public Wilder() throws IOException {
        Config.INSTANCE.loadConfiguration();
        int PORT = Integer.parseInt(Config.INSTANCE.getConfigVar(Config.PORT));

        serverSocket = new ServerSocket(PORT);
        controller = new Controller();

        logger = Logger.INSTANCE;
    }

    public static void main(String[] args) {
        try {
            new Wilder().startServer();
        } catch (IOException ex) {
            ex.printStackTrace();
        }
    }

    public void startServer() {
        if (!running) {
            running = true;
            try {
                logger.log("Starting server...");
                while (running) {
                    Socket clientSocket = serverSocket.accept();
                    controller.delegatePetition(clientSocket);
                }
            } catch (IOException ex) {
                Logger.INSTANCE.logError("Error al aceptar socket!", ex);
            }
        }
    }

    public void stopServer() {
        if (running) {
            running = false;
            logger.log("Stopping server...");
        }
    }
}
